<template>
  <CustomScrollbar class="library-scroll">
    <div class="library">
      <div class="library-header">
        <h1 class="library-title">音乐库</h1>
        <div class="library-info">
          <span class="music-count">{{ totalSongs }} 首歌曲</span>
        </div>
      </div>
      
      <!-- 分类筛选 -->
      <div class="category-filters">
        <button 
          v-for="category in categories" 
          :key="category.id"
          :class="['filter-btn', { active: selectedCategory === category.id }]"
          @click="selectCategory(category.id)"
        >
          {{ category.name }}
        </button>
      </div>
      
      <!-- 音乐表格 -->
      <div v-if="filteredSongs.length === 0" class="empty-state">
        <div class="empty-icon">
          <svg width="64" height="64" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
          </svg>
        </div>
        <h3>{{ selectedCategory === 'all' ? '音乐库空空如也' : '该分类暂无音乐' }}</h3>
        <p>{{ selectedCategory === 'all' ? '开始添加一些音乐到你的音乐库' : '尝试选择其他分类查看音乐' }}</p>
      </div>
      
      <div v-else class="music-table">
        <!-- 表格头部 -->
        <div class="table-header">
          <div class="header-cell header-index">#</div>
          <div class="header-cell header-title">标题</div>
          <div class="header-cell header-artist">艺人</div>
          <div class="header-cell header-category">分类</div>
          <div class="header-cell header-duration">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M8 3.5a.5.5 0 0 0-1 0V9a.5.5 0 0 0 .252.434l3.5 2a.5.5 0 0 0 .496-.868L8 8.71V3.5z"/>
              <path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm7-8A7 7 0 1 1 1 8a7 7 0 0 1 14 0z"/>
            </svg>
          </div>
          <div class="header-cell header-actions"></div>
        </div>
        
        <!-- 表格内容 -->
        <div class="table-body">
          <div 
            v-for="(song, index) in filteredSongs" 
            :key="song.id"
            class="table-row"
            @mouseenter="hoveredRow = index"
            @mouseleave="hoveredRow = null"
          >
            <!-- 序号/播放按钮 -->
            <div class="table-cell cell-index">
              <span v-if="hoveredRow !== index" class="track-number">{{ index + 1 }}</span>
              <button v-else class="play-btn" @click="playMusic(song)" title="播放">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                  <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
                  <path d="M6.271 5.055a.5.5 0 0 1 .52.038L11 7.055a.5.5 0 0 1 0 .89L6.791 9.907a.5.5 0 0 1-.791-.389V5.482a.5.5 0 0 1 .271-.427z"/>
                </svg>
              </button>
            </div>
            
            <!-- 标题和封面 -->
            <div class="table-cell cell-title">
              <div class="title-content">
                <div class="song-cover">
                  <img v-if="song.cover" :src="song.cover" :alt="song.name" />
                  <MusicIcon v-else :size="40" />
                </div>
                <div class="song-info">
                  <div class="song-name">{{ song.name }}</div>
                </div>
              </div>
            </div>
            
            <!-- 艺人 -->
            <div class="table-cell cell-artist">
              <span>{{ song.singer }}</span>
            </div>
            
            <!-- 分类 -->
            <div class="table-cell cell-category">
              <span 
                class="category-tag" 
                :style="{ backgroundColor: getCategoryColor(song.categoryId) }"
              >
                {{ song.categoryName }}
              </span>
            </div>
            
            <!-- 时长 -->
            <div class="table-cell cell-duration">
              <span>{{ formatDuration(song.duration) }}</span>
            </div>
            
            <!-- 操作按钮 -->
            <div class="table-cell cell-actions">
              <div class="action-buttons" v-show="hoveredRow === index">
                <button 
                  class="action-btn favorite-btn" 
                  @click="toggleFavorite(song)"
                  :class="{ 'favorited': isFavorite(song.id) }"
                  title="收藏/取消收藏"
                >
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                    <path d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"/>
                  </svg>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </CustomScrollbar>
</template>

<script>
import MusicIcon from '@/components/MusicIcon.vue'
import CustomScrollbar from '@/components/CustomScrollbar.vue'
import { musicAPI, categoryAPI } from '@/utils/api'

export default {
  components: {
    MusicIcon,
    CustomScrollbar
  },
  name: 'LibraryView',
  data() {
    return {
      selectedCategory: 'all',
      categories: [{ id: 'all', name: '全部' }],
      songs: [],
      loading: false,
      hoveredRow: null
    }
  },
  
  computed: {
    filteredSongs() {
      if (this.selectedCategory === 'all') {
        return this.songs
      }
      return this.songs.filter(song => song.categoryId === this.selectedCategory)
    },
    
    totalSongs() {
      return this.filteredSongs.length
    },
    
    favorites() {
      return this.$store.state.player.favorites || []
    }
  },
  
  async mounted() {
    await this.loadData()
    // 加载收藏列表
    await this.$store.dispatch('player/loadFavorites')
  },
  
  methods: {
    async loadData() {
      this.loading = true
      try {
        await Promise.all([
          this.loadCategories(),
          this.loadSongs()
        ])
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$toast?.error('加载数据失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    
    async loadCategories() {
      try {
        const response = await categoryAPI.getAllCategories()
        if (response.success && response.categories) {
          const apiCategories = response.categories
            .filter(cat => cat.status === 1)
            .map(cat => ({
              id: cat.categoryId,
              name: cat.name,
              color: cat.color,
              gradient: cat.gradient
            }))
          this.categories = [{ id: 'all', name: '全部' }, ...apiCategories]
        }
      } catch (error) {
        console.error('加载分类失败:', error)
      }
    },
    
    async loadSongs() {
      try {
        const response = await musicAPI.getAllMusic(0, 1000)
        if (response.success && response.music) {
          this.songs = response.music.map(music => ({
            id: music.musicId,
            name: music.name || music.title,
            singer: music.singer || music.artist,
            album: music.album || '未知专辑',
            categoryId: music.category?.categoryId || null,
            categoryName: music.category?.name || '未知分类',
            duration: music.duration,
            cover: music.coverPath ? this.buildCoverUrl(music.coverPath) : null,
            filePath: music.filePath,
            isExternal: music.filePath && (music.filePath.startsWith('http') || music.filePath.includes('url:')),
            playCount: music.playCount || 0,
            likeCount: music.likeCount || 0
          }))
        }
      } catch (error) {
        console.error('加载音乐失败:', error)
      }
    },
    
    buildCoverUrl(coverPath) {
      if (!coverPath) return null
      if (coverPath.startsWith('http')) return coverPath
      return `${process.env.VUE_APP_API_BASE_URL || 'http://localhost:2025'}${coverPath}`
    },
    
    selectCategory(categoryId) {
      this.selectedCategory = categoryId
    },
    
    getCategoryColor(categoryId) {
      const category = this.categories.find(cat => cat.id === categoryId)
      return category?.color || '#888888'
    },
    
    formatDuration(seconds) {
      // 处理各种输入情况
      if (seconds === null || seconds === undefined || seconds === 0) return '-'
      
      // 确保是数字类型
      const numSeconds = Number(seconds)
      if (isNaN(numSeconds) || numSeconds < 0) return '-'
      
      // 计算分钟和秒
      const minutes = Math.floor(numSeconds / 60)
      const remainingSeconds = Math.floor(numSeconds % 60)
      
      // 格式化输出
      if (minutes >= 60) {
        // 超过1小时的情况
        const hours = Math.floor(minutes / 60)
        const remainingMinutes = minutes % 60
        return `${hours}:${remainingMinutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
      } else {
        // 普通情况：分:秒
        return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
      }
    },
    
    async playMusic(song) {
      try {
        const musicData = {
          musicId: song.id,
          name: song.name,
          title: song.name,
          singer: song.singer,
          artist: song.singer,
          coverPath: song.cover,
          filePath: song.filePath,
          duration: song.duration,
          category: {
            categoryId: song.categoryId,
            name: song.categoryName
          }
        }
        
        await this.$store.dispatch('player/playMusic', musicData)
        this.$store.dispatch('player/setPlaylist', this.filteredSongs.map(s => ({
          musicId: s.id,
          name: s.name,
          title: s.name,
          singer: s.singer,
          artist: s.singer,
          coverPath: s.cover,
          filePath: s.filePath,
          duration: s.duration,
          category: {
            categoryId: s.categoryId,
            name: s.categoryName
          }
        })))
      } catch (error) {
        console.error('播放音乐失败:', error)
        this.$toast?.error('播放失败，请稍后重试')
      }
    },
    
    async toggleFavorite(song) {
      try {
        const musicData = {
          musicId: song.id,
          name: song.name,
          title: song.name,
          singer: song.singer,
          artist: song.singer,
          coverPath: song.cover,
          filePath: song.filePath,
          duration: song.duration
        }
        
        await this.$store.dispatch('player/toggleFavorite', musicData)
      } catch (error) {
        console.error('收藏操作失败:', error)
        this.$toast?.error('收藏操作失败，请稍后重试')
      }
    },
    
    isFavorite(musicId) {
      return this.$store.getters['player/favorites'].includes(musicId)
    },
    
    showMoreOptions(song) {
      // 显示更多选项菜单的逻辑
      console.log('显示更多选项:', song)
    }
  }
}
</script>

<style scoped>
.library-scroll {
  height: 100%;
}

.library {
  padding-bottom: 24px;
  background: linear-gradient(135deg, #1a1a1a 0%, #0d0d0d 100%);
  min-height: 100%;
}

.library-header {
  padding: 32px 32px 16px;
  background: linear-gradient(135deg, rgba(29, 185, 84, 0.1) 0%, transparent 50%);
}

.library-title {
  font-size: 2.5rem;
  font-weight: 900;
  color: white;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.library-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.music-count {
  color: #b3b3b3;
  font-size: 0.9rem;
}

.category-filters {
  display: flex;
  gap: 8px;
  padding: 0 32px 24px;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.category-filters::-webkit-scrollbar {
  display: none;
}

.filter-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: #b3b3b3;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 0.85rem;
  font-weight: 500;
  white-space: nowrap;
  cursor: pointer;
  transition: all 0.2s ease;
}

.filter-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  color: white;
}

.filter-btn.active {
  background: #1db954;
  border-color: #1db954;
  color: white;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 32px;
  text-align: center;
}

.empty-icon {
  color: #535353;
  margin-bottom: 24px;
  opacity: 0.7;
}

.empty-state h3 {
  color: white;
  font-size: 1.5rem;
  font-weight: 700;
  margin: 0 0 8px 0;
}

.empty-state p {
  color: #b3b3b3;
  font-size: 0.9rem;
  margin: 0;
}

.music-table {
  padding: 0 32px;
}

.table-header {
  display: grid;
  grid-template-columns: 60px 1fr 200px 140px 80px 120px;
  gap: 16px;
  padding: 12px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  margin-bottom: 8px;
}

.header-cell {
  color: #b3b3b3;
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  display: flex;
  align-items: center;
}

.header-duration {
  justify-content: center;
}

.table-body {
  min-height: 200px;
}

.table-row {
  display: grid;
  grid-template-columns: 60px 1fr 200px 140px 80px 120px;
  gap: 16px;
  padding: 8px 0;
  border-radius: 4px;
  transition: background-color 0.2s ease;
  cursor: pointer;
}

.table-row:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.table-cell {
  display: flex;
  align-items: center;
  color: #b3b3b3;
  font-size: 0.9rem;
}

.cell-index {
  justify-content: center;
}

.track-number {
  color: #b3b3b3;
  font-weight: 500;
}

.play-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 4px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.play-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  transform: scale(1.1);
}

.title-content {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
}

.song-cover {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.song-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.song-info {
  min-width: 0;
  flex: 1;
}

.song-name {
  color: white;
  font-weight: 500;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}



.cell-artist span {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.table-row:hover .cell-artist span,
.table-row:hover .cell-category span {
  color: white;
}

.category-tag {
  background: #535353;
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
  white-space: nowrap;
}

.cell-duration {
  justify-content: center;
  font-variant-numeric: tabular-nums;
}

.action-buttons {
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.table-row:hover .action-buttons {
  opacity: 1;
}

.action-btn {
  background: none;
  border: none;
  color: #b3b3b3;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.action-btn:hover {
  color: white;
  background: rgba(255, 255, 255, 0.1);
  transform: scale(1.1);
}

.favorite-btn.favorited {
  color: #1db954 !important;
}

.favorite-btn.favorited svg {
  color: #1db954 !important;
}

.favorite-btn.favorited:hover {
  color: #1ed760 !important;
}

.favorite-btn.favorited:hover svg {
  color: #1ed760 !important;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .table-header,
  .table-row {
    grid-template-columns: 50px 1fr 150px 100px 70px 100px;
    gap: 12px;
  }
  
  .library-header {
    padding: 24px 24px 16px;
  }
  
  .music-table {
    padding: 0 24px;
  }
  
  .category-filters {
    padding: 0 24px 24px;
  }
}

@media (max-width: 768px) {
  .table-header,
  .table-row {
    grid-template-columns: 40px 1fr 80px 80px;
    gap: 8px;
  }
  
  .header-artist,
  .header-category,
  .cell-artist,
  .cell-category {
    display: none;
  }
  
  .library-title {
    font-size: 2rem;
  }
  
  .library-header {
    padding: 20px 16px 12px;
  }
  
  .music-table {
    padding: 0 16px;
  }
  
  .category-filters {
    padding: 0 16px 20px;
  }
}
</style>